import type { IUserInfoVo, IUserLogin } from '@/api/types/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getUserInfo as _getUserInfo,
  login as _login,
  logout as _logout,
  wxLogin as _wxLogin,
  getWxCode,
} from '@/api/login'

import { showToastAsync, toast } from '@/utils/toast'

// 初始化状态
const userInfoState: IUserInfoVo = {
  userId: 0,
  userName: '',
  groupName: '',
  groupId: 0,
  phonenumber: '',
  sex: 0,
  email: '',
  dept: [],
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>({ ...userInfoState })
    // 定义用户头像
    const userAvatar = ref<string>('/src/static/person.png')
    // 定义用户是否是人大代表
    const isRepresentative = ref<number>(0)
    /** 保存 token 信息 */
    const saveTokens = (data: IUserLogin) => {
      console.log('保存token')

      uni.setStorageSync('ACCESS_TOKEN', data.accessToken)
      uni.setStorageSync('REFRESH_TOKEN', data.refreshToken)
    }
    // 设置用户信息
    const setUserInfo = (val: any) => {
      // console.log('设置用户信息', val)
      // uni.setStorageSync('userInfo', val)
      userInfo.value = {
        ...val.user,
        groupId: val.groupId ?? 0,
        groupName: val.groupName ?? '游客',
      }
    }
    // 设置用户头像
    const setUserAvatar = (avatar: string) => {
      console.log('avatar头像', avatar)

      userAvatar.value = avatar
    }
    // 设置用户是否为人大代表（0为'否'，1为'是')
    const setIsRepresentative = (flag: number) => {
      isRepresentative.value = flag
      console.log('userInfo', userInfo.value)
    }

    /**
     * 获取用户信息
     */
    /** 获取用户信息 */
    const getUserInfo = async () => {
      console.log('执行了没')

      const res = await _getUserInfo()
      if (res?.code !== 0) {
        toast.error(res?.msg || '获取用户信息失败')
        return
      }

      const data = res.data as any
      if (!data || !data.user) {
        toast.error('用户信息缺失')
        return
      }
      console.log('获取用户信息', data)
      setUserInfo(data)
      const info = data.user
      if (info.avatar) {
        setUserAvatar(info.avatar)
      }
      else {
        setUserAvatar('/static/person.png')
      }

      // 判断是否为人大代表（根据 groupId 是否存在）
      setIsRepresentative(data.groupId ? 1 : 0)

      return res
    }

    /**
     * 用户登录
     * @param credentials 登录参数
     * @returns R<IUserLogin>
     */
    const login = async (credentials: {
      username: string
      password: string
      captchaVerification?: string
      // code: string
      // uuid: string
    }) => {
      try {
        const res: IResData<IUserLogin> = await _login(credentials)
        if (res?.code === 0) {
          await showToastAsync('登录成功')
          console.log('登录成功', res.data)

          saveTokens(res.data)
          await getUserInfo()
          return true
        }
        else {
          await showToastAsync(res.msg || '登录失败', 1500, 'none')
          return false
        }
      }
      catch (err) {
        console.error('登录异常:', err)
        toast.error('登录异常，请稍后再试')
        return false
      }
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('ACCESS_TOKEN')
      uni.removeStorageSync('REFRESH_TOKEN')
    }
    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async () => {
      // 获取微信小程序登录的code
      const data = await getWxCode()
      console.log('微信登录code', data)

      const res = await _wxLogin(data)
      getUserInfo()
      return res
    }

    return {
      userInfo,
      userAvatar,
      isRepresentative,
      login,
      wxLogin,
      setUserInfo,
      getUserInfo,
      removeUserInfo,
      setUserAvatar,
      logout,
    }
  },
  {
    persist: true,
  },
)
